package com.pengpai.pangucms.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pengpai.pangucms.VO.MenuVO;
import com.pengpai.pangucms.VO.PermissionVO;
import com.pengpai.pangucms.entity.SysPermission;
import com.pengpai.pangucms.entity.SysRole;
import com.pengpai.pangucms.entity.SysRolePermission;
import com.pengpai.pangucms.entity.SysUser;
import com.pengpai.pangucms.service.ISysPermissionService;
import com.pengpai.pangucms.service.ISysRolePermissionService;
import com.pengpai.pangucms.service.ISysRoleService;
import com.pengpai.pangucms.utils.*;
import jakarta.annotation.Resource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.yaml.snakeyaml.events.Event;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Controller
@RequestMapping("/sysRole")
public class SysRoleController {
    @Resource
    private ISysRoleService sysRoleService;

    @Resource
    private ISysRolePermissionService sysRolePermissionService;

    @Resource
    private ISysPermissionService sysPermissionService;

    @GetMapping("index")
    @PreAuthorize("hasAuthority('sys:role:read')")
    public String index(){
        return "admin/sys_role/sys_role_index";
    }

    @GetMapping("add")
    @PreAuthorize("hasAuthority('sys:role:update')")
    public String add(){
        return "admin/sys_role/sys_role_add";
    }

    @GetMapping("edit")
    @PreAuthorize("hasAuthority('sys:role:update')")
    public String edit(Model model, Long id){
        SysRole role = sysRoleService.getById(id);
        model.addAttribute("role",role);
        return "admin/sys_role/sys_role_edit";
    }
    @GetMapping("list")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:read')")
    public Map<String,Object> list(String key, int page, int limit){

        Page<SysRole> sysRolePage = new Page<>(page,limit);

        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(key), "role_name", key).orderByAsc("order_id");

        List<SysRole> sysUserList = sysRoleService.page(sysRolePage,queryWrapper).getRecords();

        Map<String, Object> map = new HashMap<>();

        map.put("code",0);
        map.put("msg","");
        map.put("count",sysRolePage.getTotal());
        map.put("data",sysUserList);
        map.put("key",key);

        return map;
    }
    @PostMapping("create")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:create')")
    public R create(SysRole sysRole){

        sysRole.setCreateUser(UserUtils.CurrentUserName());
        sysRole.setCreateTime(LocalDateTime.now());
        sysRole.setUpdateUser(UserUtils.CurrentUserName());
        sysRole.setUpdateTime(LocalDateTime.now());

        sysRoleService.save(sysRole);
        return R.success();
    }

    @PostMapping("/del")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public R del(String ids){

        List<Long> list = null;
        if(StrUtil.isNotBlank(ids)){
            list = Stream.of(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        }
        sysRoleService.removeBatchByIds(list);
        return R.success();
    }

    @PostMapping("/update")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:update')")
    public R update(SysRole sysRole){


        sysRole.setCreateTime(LocalDateTime.now());
        sysRole.setUpdateUser(UserUtils.CurrentUserName());
        sysRole.setUpdateTime(LocalDateTime.now());
        sysRoleService.updateById(sysRole);
        return R.success();
    }

    @GetMapping("/permissionTree")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:grant')")
    public List<PermissionVO> permissionTree(){

        List<SysPermission> permissions = sysPermissionService.getBaseMapper().selectList(null);

        List<PermissionVO> menuList = new ArrayList<>();
        for (SysPermission permission : permissions) {
            PermissionVO per = new PermissionVO();
            per.setId(permission.getPermissionId());
            per.setPid(permission.getParentId());
            per.setTitle(permission.getPermissionName());
            menuList.add(per);
        }
        List<PermissionVO> collect = menuList.stream().filter(m -> m.getPid() == 0).map(
                (m) -> {
                    m.setChildren(TreeUtil.getChildrens(m,menuList));
                    return m;
                }
        ).collect(Collectors.toList());
        return collect;
    }

    @GetMapping("getpermissionbyid")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:read')")
    public List<Long> getPermissionById(Long id){
        QueryWrapper<SysRolePermission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role_id", id);
        List<SysRolePermission> roleFunctions = sysRolePermissionService.getBaseMapper().selectList(queryWrapper);
        List<Long> permissionById = new ArrayList<>();
        for(SysRolePermission sysRolePermission: roleFunctions){
            Long permissionId = sysRolePermission.getPermissionId();
            permissionById.add(permissionId);
        }
        return permissionById;
    }

    @PostMapping("/updateRolePermission")
    @ResponseBody
    @PreAuthorize("hasAuthority('sys:role:grant')")
    public R updateRolePermission(String ids,Long roleId){
        sysRolePermissionService.updateRolePermission(roleId,ids);
        return R.success();
    }

    @GetMapping("grant")
    @PreAuthorize("hasAuthority('sys:role:grant')")
    public String grant(Long id, Model model){
        SysRole role = sysRoleService.getById(id);
        model.addAttribute("role",role);
        return "admin/sys_role/sys_role_grant";
    }
}

